package action;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;
import org.hibernate.Transaction;

import sessionfactory.HibernateSessionFactory;
import classes.Produit;
import classes.Ventes;


public class BuyAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception 
	{
		if (request.getParameter("product") != null)
		{
			Session session = HibernateSessionFactory.getSessionFactory().openSession();
			String req = "FROM Produit WHERE id = " + request.getParameter("product");
			Transaction tx = session.beginTransaction();
			List<Produit> l = session.createQuery(req).list();
			
			Date now = new Date();
		    long nowLong = now.getTime();

			if (l != null && l.size() > 0 && l.get(0).getNombreRayon() > 0)
			{
				req = "UPDATE Produit SET nombreRayon = " + (l.get(0).getNombreRayon() - 1) + " WHERE id = " + request.getParameter("product");
				session.createQuery(req).executeUpdate();
				
				Ventes  toadd = new Ventes ();
				
				toadd.setIdProduit(Integer.valueOf(request.getParameter("product")));
				toadd.setNum(1);
				toadd.setTime(nowLong);
				toadd.setMarge(l.get(0).getMarge());
				toadd.setPrixHt(l.get(0).getPrixHt());

				session.save(toadd);
				tx.commit ();
			}
			else
				return mapping.findForward("error");
			
			return mapping.findForward("success");
		}
		return mapping.findForward("error");
	}
}